<?php

/**
 * Get value of form field
 * 
 * @package Rapide_View
 *
 */
class Rapide_View_Helper_Value extends Rapide_View_Helper
{
	/**
	 * Get value of form field
	 *
	 * Returns value of given field. If unless parameter has been passed,
	 * it will use it if value of given field is empty. If last parameter is
	 * set to true, will return value="example". If it is false, will return
	 * only "example"
	 *
	 * @param string $sField
	 * @param string $sUnless
	 * @param string $bAsAttribute return only value or with html tags
	 */
	public function execute($sField, $sUnless = null, $bAsAttribute = true, $bHtmlEntities = true)
	{
		$oRequest = new Rapide_Request;

		$sValue = null;

		if($this->_isArrayField($sField))
		{
			$aField = $this->_arrayFieldToArray($sField);
			$sField = $aField['name'];

			$aEntries = $aField['entries'];

			$aValue = $oRequest->Request(false, false, $bHtmlEntities)->get($sField);

			if(is_array($aValue))
			{
				foreach($aEntries as $sEntry)
				{
					if(is_array($aValue) && array_key_exists($sEntry, $aValue))
					{
						$aValue = $aValue[$sEntry];
					}
					else
					{
						$aValue = null;
						break;
					}
				}

				$sValue = $aValue;
			}
		}
		else
		{
			$sValue = $oRequest->Request(false, false, $bHtmlEntities)->get($sField);
		}

		if(is_null($sValue))
		{
			if(!is_null($sUnless))
			{
				$sValue = $sUnless;
			}
			else
				return;
		}

		return $bAsAttribute ? 'value="'.$sValue.'"' : $sValue;
	}

	/**
	 * Check if field name is an array field
	 *
	 * Will return true if field name is simillar to field[] or fiel[1][56]
	 * or something like that.
	 *
	 * @param string $sField
	 * @return bool true if is array field or false if is not
	 */
	private function _isArrayField($sField)
	{
		return (bool)preg_match('/^([a-zA-Z_]+)(\[.*\]+)$/', $sField);
	}

	/**
	 * Convert array field name to array
	 *
	 * For example: for "field[1][2][example]" will return
	 * array
	 * (
	 *	 'name' => 'field',
	 *	 'entries' => array(1, 2, 'example')
	 * )
	 *
	 * @param string $sField
	 * @return array with field name and with entries
	 */
	private function _arrayFieldToArray($sField)
	{
		$aMatches = array();

		preg_match('/^([a-zA-Z_]+)(\[.*\]+)$/', $sField, $aMatches);

		$sName	 = $aMatches[1];
		$sArrays = $aMatches[2];

		$aMatches = array();

		preg_match_all('/\[([a-zA-Z0-9_]*)\]/', $sArrays, $aMatches);

		$aEntries = $aMatches[1];

		return array('name' => $sName, 'entries' => $aEntries);
	}
}
?>